package com.example.algorithm.aPrimarySort;

import com.alibaba.fastjson.JSON;

/**
 * @author: dangwen
 * @createDate: 2022/4/26
 * 快速排序：二路快排
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] nums = {4,5,1,2,3,7,8};
        quickSort(nums, 0, nums.length - 1);
        System.out.println(JSON.toJSONString(nums));
    }
    public static void quickSort(int[] nums, int left, int right){
        if (left >= right){
            return;
        }
        int index = partition(nums, left, right);
        quickSort(nums, left, index - 1);
        quickSort(nums, index + 1, right);
    }

    private static int partition(int[] nums, int left, int right) {
        int lo = 0;
        int hi = 0;
        int pivot = nums[right];
        for (; hi < right; hi++){
            if (nums[hi] < pivot){
                swap(nums, lo, hi);
                lo++;
            }
        }
        swap(nums, lo ,right);
        return lo;
    }

    private static void swap(int[] nums, int lo, int hi) {
        int temp = nums[lo];
        nums[lo] = nums[hi];
        nums[hi] = temp;
    }
}
